const spinButton = document.getElementById('spinButton');
const resultModal = document.getElementById('resultModal');
const resultText = document.getElementById('resultText');
const closeButtons = document.querySelectorAll('.close');
const wheel = document.getElementById("companyList");
const projectListPage = document.getElementById('projectListPage');
const closeList = document.getElementById('closeList');
const projectSelect = document.getElementById('projectSelect');
const selectOne = document.getElementById('selectOne');
const projectName = document.getElementById('projectName');
const projectId = document.getElementById('projectId');
closeButtons.forEach(button => {
    button.onclick = () => {
        resultModal.style.display = 'none';
    }
});

closeList.onclick = () => {
    projectListPage.style.display = 'none';
}

projectSelect.onclick = () => {
    projectListPage.style.display = 'flex';
}

selectOne.onclick = () => {
    var rows = document.getElementsByTagName('tr');
    var row;
    for (var i = rows.length; i-- > 0;) {
        if (rows[i].className  ===  'selected') {
            row = rows[i];
            console.log(row)
        }
    }

    if (!row) {
        lightyear.notify('请先选择项目！', 'danger', 2000);
    }

    var tds = row.querySelectorAll("td");
    projectId.value = tds[0].innerText;
    projectName.value = tds[2].innerText;
    projectListPage.style.display = 'none';
};


spinButton.addEventListener('click', () => {
    lightyear.loading('show');

    let currentSegment = 0;
    if (projectId.value === "") {
        lightyear.notify('请先选择竞标项目！', 'danger', 2000);
        lightyear.loading('hide');
        return;
    }
    console.log( projectName.value)
    const segments = document.querySelectorAll('.segment');
    const totalSegments = segments.length;
    const rounds = 3; // Number of full rounds
    const targetSegment = Math.floor(Math.random() * totalSegments);
    const totalSteps = rounds * totalSegments + targetSegment;
    let step = 0;
    const interval = setInterval(() => {
        segments.forEach((segment, index) => {
            segment.style.backgroundColor = (index === currentSegment) ? 'orange' : 'lightblue';
        });

        if (step >= totalSteps) {
            clearInterval(interval);
            var prize = segments[currentSegment].textContent;
            var companyId = segments[currentSegment].id;
            var projectIdVal = projectId.value;
            var projectNameVal = projectName.value;
            add(projectIdVal, companyId,projectNameVal, prize);
            var currentTime = getCurrentTime();
            resultText.textContent = `${currentTime} ${projectNameVal}项目抽取完成，抽中了${prize}!`;
            resultModal.style.display = 'flex';
            lightyear.loading('hide');
        } else {
            currentSegment = (currentSegment + 1) % totalSegments;
            step++;
        }
    }, 100);
});

function getCurrentTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    // const hours = now.getHours().toString().padStart(2, '0');
    // const minutes = now.getMinutes().toString().padStart(2, '0');
    // const seconds = now.getSeconds().toString().padStart(2, '0');
    // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return `${year}-${month}-${day}`;
}
window.onclick = (event) => {
    if (event.target === resultModal) {
        resultModal.style.display = 'none';
    }
};

document.getElementById('projectList').addEventListener('click',
    function(e) {
        var rows = this.getElementsByTagName('tr');
        for (var i = rows.length; i-- > 0;) {
            rows[i].className = rows[i] === e.target.parentNode ? 'selected' : '';
        }
});

$(function(){
    $(".noneDisplay").hide();
    list();
});

function list() {
    $.ajax({
        type: "POST",
        url: "http://localhost:18600/gift/list",
        dataType: "json",
        date: {},
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var row = data.row;
            // console.log(row)
            // if (row) {
            //     wheel.style.gridTemplateColumns  = 'repeat(' + row + ', 1fr)';
            //     wheel.style.gridTemplateRows = 'repeat(' + row + ', 1fr)';
            // }
            var companyList = data.companyList;
            for (var i = 0; i < companyList.length; i++) {
                var rowNum = Math.ceil((i+1) / row);
                var columnNum = (i+1) % row;
                if ((i+1) % row === 0) {
                    columnNum = row;
                }

                var str = '<div class="segment" id="' + companyList[i].id + '" name="' + companyList[i].companyName + '">' + companyList[i].companyName + '</div>';
                $('#companyList').append(str);
            }
            var projectList = data.projectList;
            for (var i = 0; i < projectList.length; i++) {
                var str = '<tr> <td style="display: none">' + projectList[i].id + "</td><td>" + projectList[i].projectCode + "</td><td>" + projectList[i].projectName + '</td> </tr>';
                $('#projectList').append(str);
            }
        }
    });
}

function add(projectId, companyId,projectName, companyName) {
    console.log(projectId)
    console.log(companyId)
    $.ajax({
        type: "POST",
        url: "http://localhost:18600/gift/history/add",
        dataType: "json",
        data: JSON.stringify({projectId: projectId, companyId: companyId,projectName: projectName, companyName: companyName}),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.code === 200){
                // lightyear.notify('竞标完成', 'success', 2000);
            }else {
                lightyear.notify('竞标失败,失败原因：'+ data.message, 'danger', 2000);
            }
        }
    });
}